package fun.yizhierha.tools.other.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun.yizhierha.common.base.BaseErrDto;
import fun.yizhierha.common.config.FileProperties;
import fun.yizhierha.common.exception.BadRequestException;
import fun.yizhierha.common.exception.InternalServerException;
import fun.yizhierha.common.utils.PageUtils;
import fun.yizhierha.common.utils.Query;
import fun.yizhierha.common.utils.ValidList;
import fun.yizhierha.common.utils.file.ExcelUtils;
import fun.yizhierha.common.utils.file.FileUtil;
import fun.yizhierha.tools.other.domain.ToolQiniuConfig;
import fun.yizhierha.tools.other.domain.ToolQiniuContent;
import fun.yizhierha.tools.other.domain.vo.UpdateToolQiniuContentVo;
import fun.yizhierha.tools.other.domain.vo.RetrieveToolQiniuContentVo;
import fun.yizhierha.tools.other.mapper.ToolQiniuContentMapper;
import fun.yizhierha.tools.other.service.ToolQiniuConfigService;
import fun.yizhierha.tools.other.service.mapstruct.ToolQiniuContentMapstruct;
import fun.yizhierha.tools.other.service.ToolQiniuContentService;
import fun.yizhierha.tools.other.utils.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

/** generated by EH-Admin
* @author erha
* @date Sun Jan 08 14:05:28 CST 2023
**/
@Service
@RequiredArgsConstructor
public class ToolQiniuContentServiceImpl extends ServiceImpl<ToolQiniuContentMapper, ToolQiniuContent> implements ToolQiniuContentService{

    @Autowired
    private ToolQiniuConfigService toolQiniuConfigService;
    @Autowired
    FileProperties fileProperties;

    private final ToolQiniuContentMapstruct toolQiniuContentMapstruct;

    @Override
    public PageUtils<ToolQiniuContent> list(RetrieveToolQiniuContentVo retrieveToolQiniuContentVo, Query.PageVo pageVo) {
        QueryWrapper<ToolQiniuContent> wrapper = new QueryWrapper<>();
        Long contentId = retrieveToolQiniuContentVo.getContentId();
        if (contentId != null){
            wrapper.eq(ToolQiniuContent.COL_CONTENT_ID,contentId);
        }

        IPage<ToolQiniuContent> iPage = baseMapper.selectPage(new Query<ToolQiniuContent>().getPage(pageVo), wrapper);
        return new PageUtils<>(iPage);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized void edit(ValidList<UpdateToolQiniuContentVo> updateToolQiniuContentVoList, List<BaseErrDto> errDtoList) {
        List<ToolQiniuContent> toUpdateToolQiniuContentList = new ArrayList<>();

        for (UpdateToolQiniuContentVo updateToolQiniuContentVo : updateToolQiniuContentVoList) {
            Long id = updateToolQiniuContentVo.getId();
            // 1.字段为UNI，需要不重复

            ToolQiniuContent toolQiniuContent = toolQiniuContentMapstruct.toToolQiniuContent(updateToolQiniuContentVo);

            toUpdateToolQiniuContentList.add(toolQiniuContent);
        }

        // 2.更新
        this.updateBatchById(toUpdateToolQiniuContentList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> remove(Set<Long> ids) {
        List<ToolQiniuContent> toolQiniuContentList = list(new QueryWrapper<ToolQiniuContent>().in(ToolQiniuContent.COL_CONTENT_ID, ids));
        if (toolQiniuContentList.isEmpty()){
            return null;
        }

        // 获取配置
        List<ToolQiniuConfig> toolQiniuConfigList = toolQiniuConfigService.getActiveConfig();
        if (toolQiniuConfigList.isEmpty()) throw new BadRequestException("没有激活的配置[请添加配置并且激活]");
        if (toolQiniuConfigList.size() > 1) throw new InternalServerException("激活的配置不止一个");

        Map<String, Object> resMap = QiniuUtil.delFiles(toolQiniuContentList, toolQiniuConfigList.get(0));
        ArrayList<Long> successIds = (ArrayList<Long>) resMap.get("successId");
        this.removeByIds(successIds);
        if (successIds.size() != ids.size()){
            resMap.remove("successIds");
            return resMap;
        }
        return null;
    }

    @Override
    public void download(HttpServletResponse response) {
        ExcelUtils.export(response,"七牛云信息表",this.list(), ToolQiniuContent.class);
    }


    @Override
    public ToolQiniuContent save(MultipartFile file) {
        // 检查文件大小
        FileUtil.checkSize(fileProperties.getMaxSize(),file.getSize());

        // 获取配置
        List<ToolQiniuConfig> toolQiniuConfigList = toolQiniuConfigService.getActiveConfig();
        if (toolQiniuConfigList.isEmpty()) throw new BadRequestException("没有激活的配置[请添加配置并且激活]");
        if (toolQiniuConfigList.size() > 1) throw new InternalServerException("激活的配置不止一个");

        ToolQiniuConfig cfg = toolQiniuConfigList.get(0);

        ToolQiniuContent toolQiniuContent = new ToolQiniuContent();
        QiniuUtil.upload(file,cfg,toolQiniuContent);


        String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
        // 文件类型
        toolQiniuContent.setType(FileUtil.getFileType(suffix));
        // 文件后缀
        toolQiniuContent.setSuffix(suffix);
        // 创建时间
        toolQiniuContent.setUpdateTime(new Timestamp(new Date().getTime()));
        // bucket
        toolQiniuContent.setBucket(toolQiniuConfigList.get(0).getBucket());
        // size
        toolQiniuContent.setSize(FileUtil.getSize(file.getSize()));
        // url
        toolQiniuContent.setUrl(QiniuUtil.getUrl(toolQiniuContent.getName(),toolQiniuConfigList.get(0)));

        this.save(toolQiniuContent);
        return toolQiniuContent;
    }

}